package com.rcloud.server.sealtalk.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 一句话描述功能
 *
 * @author fengsong
 * @date create in 10:59 2019/1/3 2019
 */
@Component
public class RedisService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static String token_pre = "token_";
    private static String token2_pre = "token2_";
    private static String token2_split = "_s_";

    public Long getId(String key) {
        return redisTemplate.boundValueOps(key).increment(1);
    }

    public String setKeyVal(String key) {
        String val = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(key, val);
        return val;
    }

    public boolean validKey(String key, String val) {
        String store = redisTemplate.opsForValue().get(key).toString();
        return StringUtils.equals(val, store);
    }

    public String getVal(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }
    public Boolean delVal(String key) {
        return stringRedisTemplate.delete(key);
    }

    public void setVal(String key, String val) {
        stringRedisTemplate.opsForValue().set(key, val);
    }

    public void setVal(String key, String val, long seconds) {
        stringRedisTemplate.opsForValue().set(key, val, seconds, TimeUnit.SECONDS);
    }


//    public boolean valid(Long userId, String token) {
//        String result = getVal(token_pre + userId);
//        return StringUtils.isNotBlank(result) && result.equals(token);
//    }

    //token 默认设置失效100天
    public void setToken(Long userId, String token) {
        setVal(token_pre + userId, token, 8640000);

    }

    public void setToken2(Long userId, Long time, String token) {
        setVal(token2_pre + userId + token2_split + time, token, 8640000);

    }

    public String getToken(Long userId) {
        return getVal(token_pre + userId);
    }

    public String getToken2(Long userId, Long time) {
        return getVal(token2_pre + userId + token2_split + time);
    }

    public void deleteToken(Long userId) {
        stringRedisTemplate.delete(token_pre + userId);
    }

    public void deleteToken2(Long userId, Long time) {
        stringRedisTemplate.delete(token2_pre + userId + token2_split + time);
    }

}
